<?php
namespace control;

/*
*工伤管理类
*/

class staffInjuryClass extends adIndexClass
{
	private const page  = 'staffInjury';
	private const table = 'staff_injury';
	private const title = '工伤管理';
	public array $stateOption = ['草稿', '审核中', '已通过'];

	/*列表-查询条件*/
	public function home()
	{
		//生成查询表单
		$html =
			text(array("name" => "orderNo", "title" => "工伤编号")) .
			selectMultiple(["name" => "stid", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '受伤者姓名']) .
			selectMultiple(["name" => "departmentId", 'table' => " department", 'sqlId' => 'id', 'sqlField' => 'name', 'title' => '受伤者部门']) .
			select(array('name' => 'type', 'title' => '分类', 'option' => explode('，', para('staffInjuryOption')))) .
			text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "登记日期")) .
			select(array("name" => "state", "title" => "状态", "option" => $this->stateOption));
		//返回
		return $this->homeFun($this->search($html));
	}

	/*客户列表-查询结果*/
	public function homeSearch()
	{
		//like查询数组
		$like = array(
			"orderNo" => $this->post('orderNo'),//试卷编号
		);
		//全等查询数组
		$equal = array(
			"type"    => $this->post('type'),//分类
			"state"   => $this->post('state'),//状态
			"staffId" => $this->post('stid'),//姓名
		);
		$and   = $this->seeSelf(self::page, 'stid');
		if (!empty($this->post('departmentId'))) {
			//部门
			$and .= " and jobId in (select id from job where departmentId = '{$this->post('departmentId')}')";
		}
		if ($this->post('createTime')) {
			$and .= self::timeComparison($this->post('createTime'));
		}
		//获取查询结果
		$where = search(array("like" => $like, "=" => $equal)) . $and;
		$page  = $this->page(array("table" => self::table, "where" => $where, "order" => 'time desc'));
		//获取表头
		$checkAll = $this->checkAll("listForm", "listId");
		$tr[]     = array($checkAll, "工伤编号", "受伤者姓名", "受伤者部门", '分类', '发生时间', '发生地点', '受伤原因/部位', '登记日期', '状态');
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate    = array(
				"box"    => array("name" => "listId", "value" => $array['id']),
				"detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
			);
			$talent_pool = query('talent_pool', " id = '$array[talentId]'");
			$job         = query('job', " id = '$array[jobId]'");
			$department  = query('department', " id = '$job[departmentId]'");
			$tr[]        = array($this->dominate($dominate), $array['orderNo'], $talent_pool['name'], $department['name'], $array['type'], $array['startDate'], $array['address'], $array['reason'], $array['time'], $array['state']);
		}
		//控件
		$button = "";
		if ($this->power(self::page, "edit")) {
			$button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
		}
		if ($this->power(self::page, "del")) {
			$button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
		}
		//返回
		$json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 编辑页
	 *
	 * @return string
	 */
	public function edit(): string
	{
		$id     = $this->get('id') ?: suiji();
		$info   = query(self::table, " id = '" . $id . "' ");
		$staff  = query('staff', " stid = '$info[stid]'");
		$talent = query('talent_pool', " id = '$staff[talentId]'");
		$button = [];
		if ($this->power(self::page, "edit")) {
			//按钮
			$button[] = [
				"name"  => L('public.submit'),
				"type"  => "点击事件",
				"title" => "保存",
				"fun"   => "subForm('" . self::page . "EditForm',root+'control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
				'style' => 'li-btn-blue-bg',
			];
			$button[] = [
				"name"  => L('public.saveDraft'),
				"type"  => "点击事件",
				"cla"   => $this->get('cla'),
				"fun"   => "saveTemp('" . self::page . "', 'edit', '" . self::page . "EditForm')",
				"post"  => ["id" => $this->get('id')],
				'style' => 'li-btn-green-bg',
			];
		}
		//表单
		$data['html'] = $this->layerEdit([
			"table"  => [
				[
					$this->tableShowButton($button),
				],
				[
					must . "受伤者姓名：" => selectMultiple(["name" => "staffId", 'table' => " staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'title' => '姓名', 'change' => 'getStaffInfo', 'class' => 'text', "value" => $info['staffId']]),
					"身份证号："          => "<span id='idCard'>{$talent['idCard']}</span>",
				],
				[
					'分类：' => select(array('name' => 'type', 'title' => '分类', 'option' => explode('，', para('staffInjuryOption')), 'value' => $info['type'])),
				],
				[
					must . "发生时间：" => text(["name" => "startDate", 'laydate' => [], 'class' => 'text', "value" => $info['startDate']]),
					must . "发生地点：" => text(["name" => "address", 'class' => 'text', "value" => $info['address']]),
				],
				[
					must . "受伤原因(部位)：" => text(["name" => "reason", 'class' => 'long', "value" => $info['reason']]),
				],
				[
					'是否备案:'         => radio(array('name' => 'isRecord', 'value' => ['是', '否'], 'checked' => $info['isRecord'])),
					'是否申请工伤认定:' => radio(array('name' => 'isApply', 'value' => ['是', '否'], 'checked' => $info['isApply'])),
				],
				[
					'是否报保险:' => radio(array('name' => 'isInsurance', 'value' => ['是', '否'], 'checked' => $info['isInsurance'])),
					'是否鉴定:'   => radio(array('name' => 'isChecked', 'value' => ['是', '否'], 'checked' => $info['isChecked'])),
				],
				[
					"备注：" => textarea(array('name' => 'text', 'value' => $info['text'])),
				],
				[
					"附件：" => fileUploadClass::addFileComponent($info['id'], '工伤管理', self::page, self::page . 'EditForm'),
				],
			],
			'hidden' => hidden(['name' => 'id', 'value' => $info['id'] ?: $id]),
			'button' => ' ',
		]);

		$data['html'] .= <<<efo

<script>
        function getStaffInfo(e){
            $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=getStaffInfo',{id:e.value},function (res){
                $("#idCard").html(res.data.idCard);
            },'json')
        }
</script>


efo;

		//返回
		return $this->tab($data);
	}

	/**
	 *获取员工信息
	 */
	public function getStaffInfo()
	{
		$staff        = query('staff', " stid = '{$this->post('id')}'");
		$talent       = query('talent_pool', " id = '$staff[talentId]'");
		$json['data'] = [
			'idCard' => $talent['idCard'],
		];
		return json_encode($json, 320);
	}

	public function editEdit()
	{
		$id = $this->post('id') ?: self::getId();
		//附件
		$fileIdArr  = $this->post('fileId');
		$field      = [
			'staffId'     => $this->post('staffId'),
			'startDate'   => $this->post('startDate'),
			'type'        => $this->post('type'),
			'address'     => $this->post('address'),
			'reason'      => $this->post('reason'),
			'isRecord'    => $this->post('isRecord') ?: '否',
			'isApply'     => $this->post('isApply') ?: '否',
			'isInsurance' => $this->post('isInsurance') ?: '否',
			'isChecked'   => $this->post('isChecked') ?: '否',
			'text'        => $this->post('text'),
		];
		$annotation = [
			'staffId'   => '姓名',
			'startDate' => '发生时间',
			'address'   => '发生地点',
			'reason'    => '受伤原因/部位',
		];
		$rules      = [
			'staffId'   => 'required',
			'startDate' => 'required',
			'address'   => 'required',
			'reason'    => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}

		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			$staff             = query('staff', " stid = '$field[staffId]'");
			$field['jobId']    = $staff['jobId'];
			$field['talentId'] = $staff['talentId'];
			$where             = " id = '$id' ";
			$info              = query(self::table, $where);
			if (!$info['id']) {
				$userNo       = codeTemplateClass::generateCode(self::page, [
					'prefix' => 'GS' . date('Ymd'),
					'table'  => self::table,
					'field'  => 'orderNo',
					'where'  => '',
				], $field);
				$field        = array_merge($field, [
					'id'      => $id,
					'orderNo' => $userNo,
					'stid'    => $this->control['stid'],
					'state'   => '草稿',
					'time'    => $this->time,
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"])) {
				//添加主表ID到附件表
				if (is_array($fileIdArr)) {
					update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
				}
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 审核按钮
	 *
	 * @param $info
	 * @return array
	 */
	public function auditButton($info): array
	{
		$button = [];
		if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
			$button[] = [
				"name"  => '提交审批',
				"type"  => "弹出层",
				"cla"   => 'audit',
				"fun"   => "operate",
				'style' => 'li-btn-blue-bg',
				"post"  => [
					"act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'name'    => '工伤申请',
						'table'   => self::table,
						'process' => [
							// 预览函数
							'detail' => [
								'cla' => $this->get('cla'),
								'fun' => 'detail',
							],
							// 保存函数
							'save'   => [
								'cla' => $this->get('cla'),
								'fun' => 'editEdit',
							],
							//执行发起时验证函数
							'before' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
							//完成发起后执行函数
							'after'  => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
			];
		}
// 审批并判断是否有权限
		if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
			$button[] = [
				"name" => '添加审批人',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];
			$button[] = [
				"name" => '转交',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table' => self::table,
					], 320)),
				],
			];
			$button[] = [
				"name"  => '审批',
				"type"  => "弹出层",
				"cla"   => 'audit',
				"fun"   => "operate",
				// 以下参数固定格式
				"post"  => [
					"act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table'   => self::table,
						// 当前状态
						'state'   => $info['state'],
						// 变更
						'field'   => ['state'],   //变更字段 可多个
						'value'   => [
							'state' => ['草稿', '已通过'],
						],
						// 审核时回调
						'process' => [
							//执行首次审核时验证
							'before' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
							//执行末次审核后处理
							'after'  => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
				'style' => 'li-btn-blue-bg',
			];
		}

		// 撤销审批
		if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
			$button[] = [
				"name" => '撤销审批',
				"type" => "弹出层",
				"cla"  => 'audit',
				"fun"  => "operate",
				"post" => [
					"act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
						'table'   => self::table,
						// 当前状态
						'state'   => $info['state'],
						// 变更
						'field'   => ['state'],   //变更字段 可多个
						'value'   => [
							'state' => ['草稿'],
						],
						'process' => [
							//完成发起后执行函数
							'after' => [
								'cla' => $this->get('cla'),
								'fun' => '',
							],
						],
					], 320)),
				],
			];
		}
		return $button;
	}

	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			$staffProfiles = new staffProfilesClass();
			//菜单
			$data       = array(
				"id"    => $info['id'],
				"title" => self::title . '详情',
			);
			$talent     = query('talent_pool', " id = '$info[talentId]'");
			$job        = query('job', " id = '$info[jobId]'");
			$department = query('department', " id = '$job[departmentId]'");
			$entry      = query('staff_entry_record', " talentId = '$info[talentId]' order by time desc");
			$button     = [];
			if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
				//按钮
				$button[] = [
					"name"  => "编辑",
					"type"  => "顶部页卡",
					"title" => "编辑用户",
					"url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
				];
			}
			if ($this->power(self::page, "del") && $info['state'] == '草稿') {
				//按钮
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
			}
			$audit = query('audit', " targetId = '$info[id]'");
			//审核按钮
			$button = array_merge($button, $this->auditButton($info));
			//生成表单
			$data['html'] = $this->tableShow(array(
				"button"   => $button,
				array(
					array(
						"受伤者姓名" => $talent['name'],
						"受伤者部门" => $department['name'],
						"分类"       => $info['type'],
					),
					array(
						"身份证号" => $talent['idCard'],
						"性别"     => $talent['sex'],
						"年龄"     => $staffProfiles->age($talent['birthDay']),
					),
					array(
						"工龄(年)" => floor((time() - strtotime($entry['entryDate'])) / 60 / 60 / 24),
						"文化程度" => $talent['education'],
						"发生时间" => $info['startDate'],
					),
					array(
						"发生地点"       => $info['address'],
						"受伤原因(部位)" => $info['reason'],
						"是否备案"       => $info['isRecord'],
					),
					array(
						"是否申请工伤认定" => $info['isApply'],
						"是否报保险"       => $info['isInsurance'],
						"是否鉴定"         => $info['isChecked'],
					),
					array(
						"备注" => $info['text'],
					),
				),
				'系统信息' => array(
					array(
						"工伤编号" => $info['orderNo'],
						"登记人"   => self::findStaff($info['stid']),
						"登记时间" => $info['time'],
					),
					array(
						"提交时间" => self::null($audit['commitTime']),
						"状态"     => $info['state'],
					),
				),
				'附件'     => array(
					array(
						fileUploadClass::showFile($info['id'], '工伤管理'),
					),
				),
				'流程'     => array(
					array(
						auditClass::auditRecord(self::table, $info['id']),
					),
				),
			));
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}


	// 操作中转
	public function operate()
	{
		$act  = $this->post('act') ?? '';
		$pwd  = false; // 需要密码
		$form = $power = '';
		switch ($act) {
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete()
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " id = '$id' ");
				if ($info['state'] != '草稿') {
					$warn = "不是草稿状态，暂不能删除";
				} else {
					//删除audit表记录
					delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
					$all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
					foreach ($all['array'] as $val) {
						fileDelete($val['src']);
						delete(array("table" => 'file', "where" => " id = '$val[id]' "));
					}
					//删除审批记录
					delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
					//删除消息提醒
					delete(array("table" => "message", "where" => " typeId = '$id' "));
					//删除待办事项
					delete(array("table" => "backlog", "where" => " typeId = '$id' "));
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}
}

